//
//  AttributeModelVC.m
//  YZZX
//
//  Created by Easaa on 15/4/30.
//  Copyright (c) 2015年 Easaa. All rights reserved.
//

#import "AttributeModelVC.h"


//修改密码
#import "ChangeThePassword.h"
//A字体大小
#import "MassgeTheFont.h"
//使用帮助
#import "UserHelpVc.h"

//咨询
#import "ConsultingVC.h"

//版本信息
#import "VersionInformationVc.h"

//弹框代理
#import "MassgeTheFont.h"


@interface AttributeModelVC ()<UIAlertViewDelegate,MassgeTheFontDelegate,UIScrollViewDelegate>
{
    UIView  *viewbg;
    UIScrollView    *_BgScrollView;
}

@end

@implementation AttributeModelVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    self.view.backgroundColor =RGBCOLOR(235, 235, 235);
    [self createAndNewView];
}

-(void)createAndNewView
{
    
    
    // UIScrollView创建
    _BgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, Dev_ScreenHeight-64)];
    _BgScrollView.contentSize =CGSizeMake(Dev_ScreenWidth, Dev_ScreenHeight);
    _BgScrollView.delegate =self;
    //_BgScrollView.bounces = NO;
    [_BgScrollView setPagingEnabled:YES];
    //[_BgScrollView setShowsHorizontalScrollIndicator:NO];
    _BgScrollView.showsHorizontalScrollIndicator = NO;
    _BgScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_BgScrollView];
    
    
    //底部御用刷新的view
    viewbg = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Dev_ScreenWidth, Dev_ScreenHeight)];
    //viewbg.backgroundColor = [UIColor greenColor];
    [_BgScrollView addSubview:viewbg];
    
    
    //修改密码
    //字体大小设置
    UIView *viewBackground0  = [self BackgroundViewHigh];
    viewBackground0.frame = CGRectMake(5, 10, Dev_ScreenWidth-10, 80);
    [viewbg addSubview:viewBackground0];
    
    UIControl *password = [self cateStripesFantionImageName:@"settings_change_password.png" TitleText:@"修改密码"];
    password.tag=0;
    password.frame = CGRectMake(0, 0, Dev_ScreenWidth-10, 40);
    [password addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground0 addSubview:password];
    
    //分割线
    UIView * viewline = [self LineFantion];
    viewline.frame =CGRectMake(5, 39, Dev_ScreenWidth-10-10, 1);
    [password addSubview:viewline];
    
    UIControl *fontsize = [self cateStripesFantionImageName:@"settings_font_size.png" TitleText:@"字体大小设置"];
    fontsize.tag=1;
    fontsize.frame = CGRectMake(0, 40, Dev_ScreenWidth-10, 40);
    [fontsize addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground0 addSubview:fontsize];
    
    
    
    //支付
    UIView *viewBackground1  = [self BackgroundViewHigh];
    viewBackground1.frame = CGRectMake(5, 10+80+10, Dev_ScreenWidth-10, 40);
    [viewbg addSubview:viewBackground1];
    
    UIControl *PayView = [self cateStripesFantionImageName:@"settings_payment.png" TitleText:@"支付"];
    PayView.tag=2;
    PayView.frame = CGRectMake(0, 0, Dev_ScreenWidth-10, 40);
    [PayView addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground1 addSubview:PayView];

    
    
    
    //给我评分
    //使用帮助
    //建议
    //咨询
    //版本信息
    
    UIView *viewBackground2  = [self BackgroundViewHigh];
    viewBackground2.frame = CGRectMake(5, 10+80+10+40+10, Dev_ScreenWidth-10, 160);//删除版本信息修改
    [viewbg addSubview:viewBackground2];
    
    UIControl *Score = [self cateStripesFantionImageName:@"settings_grade.png" TitleText:@"给我评分"];
    Score.tag=3;
    Score.frame = CGRectMake(0, 0, Dev_ScreenWidth-10, 40);
    [Score addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground2 addSubview:Score];

    
    //分割线
    UIView * viewlineScore = [self LineFantion];
    [Score addSubview:viewlineScore];
    
    
    
    UIControl *Help = [self cateStripesFantionImageName:@"settings_help.png" TitleText:@"使用帮助"];
    Help.tag=4;
    Help.frame = CGRectMake(0, 40, Dev_ScreenWidth-10, 40);
    [Help addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground2 addSubview:Help];
    
    //分割线
    UIView * viewlineHelp = [self LineFantion];
    [Help addSubview:viewlineHelp];
    
    
    UIControl *Advice = [self cateStripesFantionImageName:@"settings_proposal.png" TitleText:@"建议"];
    Advice.tag=5;
    Advice.frame = CGRectMake(0, 80, Dev_ScreenWidth-10, 40);
    [Advice addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground2 addSubview:Advice];
    
    //分割线
    UIView * viewlineAdvice = [self LineFantion];
    [Advice addSubview:viewlineAdvice];
    
    UIControl *Consulting = [self cateStripesFantionImageName:@"settings_consulting.png" TitleText:@"咨询"];
    Consulting.tag=6;
    Consulting.frame = CGRectMake(0, 120, Dev_ScreenWidth-10, 40);
    [Consulting addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground2 addSubview:Consulting];
    
    //删除版本信息修改
    //分割线
//    UIView * viewlineConsulting = [self LineFantion];
//    [Consulting addSubview:viewlineConsulting];
//    
//    UIControl *Information = [self cateStripesFantionImageName:@"settings_version.png" TitleText:@"版本信息"];
//    Information.tag=7;
//    Information.frame = CGRectMake(0, 160, Dev_ScreenWidth-10, 40);
//    [Information addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
//    [viewBackground2 addSubview:Information];
    

    
    //缓存清理
    UIView *viewBackground3  = [self BackgroundViewHigh];
    viewBackground3.frame = CGRectMake(5, 10+80+10+10+200+10, Dev_ScreenWidth-10, 40);//删除版本信息修改 y位置
    [viewbg addSubview:viewBackground3];
    
    
    UIControl *CacheView = [self cateStripesFantionImageName:@"settings_cleanup_cache" TitleText:@"缓存清理"];
    CacheView.tag=8;
    CacheView.frame = CGRectMake(0, 0, Dev_ScreenWidth-10, 40);
    [CacheView addTarget:self action:@selector(DelegateFantion:) forControlEvents:UIControlEventTouchUpInside];
    [viewBackground3 addSubview:CacheView];
    
   
}


-(UIControl *)cateStripesFantionImageName:(NSString *)imageName TitleText:(NSString *)titleName
{
    
    UIControl *LableTiy = [[UIControl alloc]init];
    //LableTiy.backgroundColor =[UIColor greenColor];
    
    UIImageView *iamgeview = [[UIImageView alloc]initWithImage:[UIImage imageNamed:imageName]];
    iamgeview.frame =CGRectMake(8, 8, 25, 25);
    [LableTiy addSubview:iamgeview];
    
    //iamgeview.backgroundColor =[UIColor  redColor];
    
    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(40, 0, 200, 40)];
    labelTitle.font = [UIFont boldSystemFontOfSize:14.0];  //UILabel的字体大小
    labelTitle.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
    labelTitle.textColor = [UIColor grayColor];//RGBCOLOR(0, 0, 147);
    labelTitle.textAlignment = NSTextAlignmentLeft;  //文本对齐方式
    //[labelTitle setBackgroundColor:[UIColor greenColor]];
    labelTitle.text =titleName ;
    [LableTiy addSubview:labelTitle];

    
    if(![titleName isEqualToString:@"缓存清理"]&&![titleName isEqualToString:@"版本信息"]&&![titleName isEqualToString:@"字体大小设置"])
    {
   
        UIImageView *iamgeviewback = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"settings_arrow.png"]];
        iamgeviewback.frame =CGRectMake(Dev_ScreenWidth-10-40, 5, 30, 30);
        [LableTiy addSubview:iamgeviewback];
        
     
    
    }else if ([titleName isEqualToString:@"缓存清理"])
    {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        NSString *path = [paths lastObject];
        
        NSString *StrHuanCun = [NSString stringWithFormat:@"%.1fM", [self folderSizeAtPath:path]];
        
        //缓存 数据大小  显示
        UILabel *labelHuanCun = [[UILabel alloc] initWithFrame:CGRectMake(Dev_ScreenWidth-10-40-30, 0, 60, 40)];
        labelHuanCun.font = [UIFont boldSystemFontOfSize:13.0];  //UILabel的字体大小
        labelHuanCun.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
        labelHuanCun.textColor = RGBCOLOR(148, 148, 147);
        labelHuanCun.textAlignment = NSTextAlignmentRight;  //文本对齐方式
       //[labelHuanCun setBackgroundColor:[UIColor redColor]];
        labelHuanCun.text = StrHuanCun;
        [LableTiy addSubview:labelHuanCun];
    
    }else if ([titleName isEqualToString:@"版本信息"])
    {
        NSString  * app_Version =[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        app_Version = [NSString stringWithFormat:@"v%@",app_Version];
        
        //缓存 数据大小  显示
        UILabel *labelHuanCun = [[UILabel alloc] initWithFrame:CGRectMake(Dev_ScreenWidth-10-40-30, 0, 60, 40)];
        labelHuanCun.font = [UIFont boldSystemFontOfSize:13.0];  //UILabel的字体大小
        labelHuanCun.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
        labelHuanCun.textColor = RGBCOLOR(148, 148, 147);
        labelHuanCun.textAlignment = NSTextAlignmentRight;  //文本对齐方式
        //[labelHuanCun setBackgroundColor:[UIColor redColor]];
        labelHuanCun.text = app_Version;
        [LableTiy addSubview:labelHuanCun];
    
    
    }else if ([titleName isEqualToString:@"字体大小设置"])
    {
        //拿到设置字体大小设置   ---初始化设置默认哪个大小
        NSUserDefaults *UserDefaultSize =[NSUserDefaults standardUserDefaults];
        NSInteger  _NuberSize = [UserDefaultSize floatForKey:YZZX_Font_Size];
      
        
        
        NSString *strSzie =[[NSString alloc]init];
        
        if(_NuberSize == 13)
        {
            strSzie = @"小号字";
        }else if (_NuberSize == 16)
        {
            strSzie = @"中号字";
        }else if (_NuberSize == 19)
        {
            strSzie = @"大号字";
 
        }else if (_NuberSize == 22)
        {
            strSzie = @"特大号字";
        }
  
        
        //缓存 数据大小  显示
        UILabel *labelHuanCun = [[UILabel alloc] initWithFrame:CGRectMake(Dev_ScreenWidth-10-40-30, 0, 60, 40)];
        labelHuanCun.font = [UIFont boldSystemFontOfSize:13.0];  //UILabel的字体大小
        labelHuanCun.numberOfLines = 1;  //必须定义这个属性，否则UILabel不会换行
        labelHuanCun.textColor = RGBCOLOR(148, 148, 147);
        labelHuanCun.textAlignment = NSTextAlignmentRight;  //文本对齐方式
        //[labelHuanCun setBackgroundColor:[UIColor redColor]];
        labelHuanCun.text = strSzie;
        [LableTiy addSubview:labelHuanCun];
        
    }
    
    
    return LableTiy;

}

-(UIView *)BackgroundViewHigh;
{
    UIView *bgview =[[UIView alloc]init];
    bgview.backgroundColor =[UIColor whiteColor];
    [bgview.layer setMasksToBounds:YES];
    [bgview.layer setCornerRadius:5]; //设置矩圆角半径
    [bgview.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef colorref = CGColorCreate(colorSpace,(CGFloat[]){ 0, 0, 0, 0.5 });
    [bgview.layer setBorderColor:colorref];//边框颜色

    return bgview;
}

-(UIView *)LineFantion
{
   UIView *Lineview =[[UIView alloc]initWithFrame:CGRectMake(5, 39, Dev_ScreenWidth-10-10, 1)];
    Lineview.backgroundColor = RGBCOLOR(241, 241, 241);
    return Lineview;
}


#pragma mark 设置列表 点击方法
-(void)DelegateFantion:(UIControl *)controlTag
{
     if(controlTag.tag == 0)
     {
        if(![[XSZ_UICommon useridChangUaerdfLoginBoolString]isEqualToString:@""])
         {
             ChangeThePassword  *PassWordView =[[ChangeThePassword alloc]init];
             [self.navigationController pushViewController:PassWordView animated:YES];
             
         }else if ([[XSZ_UICommon useridChangUaerdfLoginBoolString]isEqualToString:@""])
         {
             
             LoginViewController  *LoginView =[[LoginViewController alloc]init];
             LoginView.Viewdegat =self.Viewdegat;
             [self.navigationController pushViewController:LoginView animated:YES];

         }
         
     }else if (controlTag.tag == 1)
     {
         MassgeTheFont *viewfont = [[MassgeTheFont alloc]initWithViewFont:[UIApplication sharedApplication].keyWindow.bounds];
         viewfont.SizeDelegat = self;
         [[UIApplication sharedApplication].keyWindow addSubview:viewfont];
     
     }else if (controlTag.tag == 2)
     {
         UIAlertView  *AlertView = [[UIAlertView alloc]initWithTitle:@"温馨提示"
                                                             message:@"此功能正在完善,请耐心等等哦!"
                                                            delegate:self
                                                   cancelButtonTitle:@"关闭"
                                                   otherButtonTitles:nil];
         
         AlertView.tag = 0;
         [AlertView show];
     
     }else if (controlTag.tag == 3)
     {

  
         NSString *  str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id995877413"];
       
         [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
         
     }else if (controlTag.tag == 4)
     {

     UserHelpVc  *consulting =[[UserHelpVc alloc]init];
     [self.navigationController pushViewController:consulting animated:YES];
     
     
     }else if (controlTag.tag == 5)
     {
     
         ConsultingVC  *consulting =[[ConsultingVC alloc]init];
         consulting.title =@"建议";
         consulting.type =@"0";
         [self.navigationController pushViewController:consulting animated:YES];
     
     }else if (controlTag.tag == 6)
     {
         ConsultingVC  *consulting =[[ConsultingVC alloc]init];
         consulting.title =@"咨询";
         consulting.type =@"1";
         [self.navigationController pushViewController:consulting animated:YES];


    }else if (controlTag.tag == 7)
    {
        VersionInformationVc  *VersionView = [[VersionInformationVc alloc]init];
        [self.navigationController pushViewController:VersionView  animated:YES];

    }else if (controlTag.tag == 8)
    {

        UIAlertView  *AlertView = [[UIAlertView alloc]initWithTitle:@"提示"
                                                            message:@"确认要清除缓存吗？"
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"确定", nil];
        
        AlertView.tag = 1024;
        [AlertView show];
        
    }

}


#pragma mark alertView 弹框代理
 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
 {
     
     if(alertView.tag == 1024)
     {
         if(buttonIndex == 0)
         {
             //取消则不清除缓存
         }else if (buttonIndex == 1)
         {
             [self action];
             
             FMDatabase  *db = [YZFMDB creatDatabase];
             if (![db open]) {
                 NSLog(@"数据库打开失败");
             }
             

             [db executeUpdate:@"DELETE FROM  MassgeWebView"];
             [viewbg removeFromSuperview];
             [self createAndNewView];
         }
     }

 }

#pragma mark 修改字体大小 刷新代理
-(void)sizeFontNumber
{
    [_BgScrollView removeFromSuperview];
    [self createAndNewView];
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//遍历文件夹获得文件夹大小，返回多少M
- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
//1. 清除缓存第一种
- (void)action;//:(id)sender
{
//    //彻底清除缓存第一种方法
//   // UIButton * button = sender;
//    //[button setTitle:@"清理完毕" forState:UIControlStateNormal];
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
//    NSString *path = [paths lastObject];
//    
//    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [self folderSizeAtPath:path]];
//    NSLog(@"%@",str);
//    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
//    for (NSString *p in files) {
//        NSError *error;
//        NSString *Path = [path stringByAppendingPathComponent:p];
//        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
//            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
//        }
//    }
    
    //2. SDImage第三方清除缓存的方法
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];
    
   // 3. 彻底清除缓存第二种方法
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    
    NSString *str = [NSString stringWithFormat:@"缓存已清除%.1fM", [self folderSizeAtPath:path]];
     NSLog(@"%@",str);
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       NSLog(@"%@", cachPath);
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
                       NSLog(@"files :%lu",(unsigned long)[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       }
                       [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];});
}
-(void)clearCacheSuccess
{
    NSLog(@"清理成功");
}


@end
